package com.yusheng.tr.multi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.yusheng.tr.common.core.entity.multi.StmtMngEntity;
import com.yusheng.tr.multi.service.IStmtMngService;
import com.yusheng.utils.JsonUtils;
import jakarta.annotation.PostConstruct;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AllService{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IStmtMngService stmtMngService;

    private final static String FILE_PATH = "C:\\mysql\\";

    private static List<String> tabels = new ArrayList<>();

    @PostConstruct
    public void init() {
        String sql = "select table_name from information_schema.tables where table_schema='ys_tr_dev'";
        tabels = jdbcTemplate.queryForList(sql, String.class);
    }

    public void test() throws Exception {
        //同步模型
        /**
         * 存数据到本地文件中
         */
        for (String tabel : tabels) {
            /**
             * 判断表名是否等于stmt_mng,除了stmt_mng不拉取，其他表需要拉取
             * 并且如果本地没有stmt，创建一个空的stmt_mng的文件
             */
            if(tabel.equals("stmt_mng")){
                File file = new File(FILE_PATH + "stmt_mng.txt");
                if( !file.exists()){
                    file.createNewFile();
                }
                continue;
            }
            String sql = "select * from " + tabel;
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
            JsonUtils.writeDataJson(FILE_PATH + tabel + ".txt", mapList);
        }
    }

    /**
     * 将文件中的数据存入MySQL中
     */
    public void push(String json) throws Exception {

        String filePath = "C:\\mysql\\stmt_mng.txt";
//        String s = JsonUtils.readDataFromJson(filePath);
        List<StmtMngEntity> stmtMngEntities = JSON.parseArray(json, StmtMngEntity.class, JSONReader.Feature.SupportSmartMatch);
        List<StmtMngEntity> entityList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(stmtMngEntities)) {
            stmtMngEntities.forEach(sl ->{
                if (sl.getStatus() != 0) {
                    stmtMngService.saveOrUpdate(sl);
                }else {
                    entityList.add(sl);
                }
            });
            JsonUtils.writeDataJson(filePath, entityList);
        }
    }
}
